$NG.AllReady(function (page, { useDataIndexChange, useUpdateRow, useUpdateRows, useBeforeClick, useValuesChange, useClick }) {
  console.log("Data ready event triggered");
  var mstform = $NG.getCmpApi("p_form_Subcontracting_Plan");
  var dgrid = $NG.getCmpApi("p_form_Subcontracting_Plan_d"); //获取表体数据
  const toolbar_top = $NG.getCmpApi("toolbar_top");
  const toolbar_dgrid = $NG.getCmpApi("toolbar_p_form_Subcontracting_Plan_d");
  ////////////////////////////////////////////////////////////--toolbar--////////////////////////////////////////////////////////////
  const toolbars = [
    { toolbar: toolbar_top, items: ["imp"] },
    { toolbar: toolbar_dgrid, items: ["attachment"] },
  ];
  toolbars.forEach(({ toolbar, items }) => {
    if (toolbar) {
      items
        .map((item) => toolbar.getItem(item)) // 提前获取所有按钮
        .filter(Boolean) // 过滤掉不存在的按钮
        .forEach((toolbarItem) => toolbarItem.setHidden()); // 隐藏按钮
    }
  });

  ////////////////////--toolbar:引用设备清单--////////////////////
  if(page.oType != 'view'){
      toolbar_dgrid.insert({
          id: "addEq",
          text: "引用深化设计清单",
          iconCls: "icon-New",
        });
  }
  useClick(async function ({ args }) {
    addEqClick();
  }, "addEq");

  ////////////////////--toolbar:保存钩子--////////////////////
  useBeforeClick(async function ({ args }) {
    //按钮点击前事件
    const _arr = dgrid.getRows();
    const _errArr = [];
    _arr.forEach((item, inde) => {
      const nfb_qty = Number(item.u_sub_qty);
      const nfb_amt = Number(item.u_nfbhs_prc);
      const jh_qty = Number(item.u_plan_qty);
      const jh_amt = Number(item.u_jhhsdj);
      if (nfb_amt * nfb_qty < jh_qty * jh_amt) {
        _errArr.push(inde + 1);
      }
    });
    if (_errArr.length !== 0) {
      const _str = _errArr.join("、");
      console.log(_str, _errArr);
      $NG.alert(`当前有明细中存在计划金额超出限制序号为：${_str}`);
      return false;
    } else {
      return true;
    }
  }, "save");

  ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
  if (mstform) {
    console.log("mstform is reayd");
    setTitle();
    FilterByPhidPc();
    getInDate();
    getProjectInfo();
    if (mstform.getItem("u_zb_type").getValue()) {
      isRead();
    }
  }

  ////////////////////--mstform:项目字段变化--////////////////////
  useValuesChange(({ args }) => {
    setTitle();
    FilterByPhidPc();
    getProjectInfo();
    getFbzbjhQtyBySbqd()
  }, "p_form_Subcontracting_Plan.phid_pc");

  ////////////////////--mstform:监听招标类型字段值--////////////////////
  useValuesChange(({ args, form }) => {
    isRead();
    $NG.updateState((updater) => {
      updater.data.p_form_Subcontracting_Plan.setProps({
        u_yztjsq: null,
        u_ydj_cnt: null,
      });
    });
    // dgrid.clearRows();
  }, "p_form_Subcontracting_Plan.u_zb_type");

  ////////////////////--mstform:业主推荐申请--////////////////////
  useValuesChange(({ args }) => {
    // dgrid.clearRows();
  }, "p_form_Subcontracting_Plan.u_yztjsq");
  useValuesChange(({ args }) => {
    // dgrid.clearRows();
    console.log(args[0].u_zbsq_type.origin.value);
    if (args[0].u_zbsq_type.origin.value == 3) {
      $NG.updateUI((updater) => {
        const fields = ["u_ywxqlx","u_ywlx"];
        fields.forEach((field) => {
          // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
          updater.fieldSetForm.p_form_Subcontracting_Plan[field].setProps({
            required: true, //必输
            hidden: false,
          });
        });
      });
    }else{
      $NG.updateUI((updater) => {
        const fields = ["u_ywxqlx","u_ywlx"];
        fields.forEach((field) => {
          // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
          updater.fieldSetForm.p_form_Subcontracting_Plan[field].setProps({
            required: false, //必输
            hidden: true,
          });
        });
      });
    }
    
  }, "p_form_Subcontracting_Plan.u_zbsq_type");
  if (mstform.getItem('u_zbsq_type').getValue() == 3) {
    $NG.updateUI((updater) => {
      const fields = ["u_ywxqlx","u_ywlx"];
      fields.forEach((field) => {
        // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
        updater.fieldSetForm.p_form_Subcontracting_Plan[field].setProps({
          required: true, //必输
          hidden: false,
        });
      });
    });
  }else{
    $NG.updateUI((updater) => {
      const fields = ["u_ywxqlx","u_ywlx"];
      fields.forEach((field) => {
        // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
        updater.fieldSetForm.p_form_Subcontracting_Plan[field].setProps({
          required: false, //必输
          hidden: true,
        });
      });
    });
  }
  ////////////////////--mstform:计划进场时间--////////////////////
  useValuesChange(({ args }) => {
    const startdt = mstform.getItem("u_plan_stdt").getValue();
    const enddt = mstform.getItem("u_plan_enddt").getValue();
    if (startdt > enddt) {
      $NG.message(`计划入场日期晚于计划完工日期`);
      mstform.getItem("u_plan_stdt").setValue("");
    }
  }, "p_form_Subcontracting_Plan.u_plan_stdt");

  ////////////////////--mstform:计划完工时间--////////////////////
  useValuesChange(({ args }) => {
    const startdt = mstform.getItem("u_plan_stdt").getValue();
    const enddt = mstform.getItem("u_plan_enddt").getValue();
    if (startdt > enddt) {
      $NG.message(`计划入场日期晚于计划完工日期`);
      mstform.getItem("u_plan_enddt").setValue("");
    }
  }, "p_form_Subcontracting_Plan.u_plan_enddt");

  ////////////////////--mstform:已定价分包合同--////////////////////
  // 切换拟分包合同后，清空表体数据
  useValuesChange(({ args }) => {
    dgrid.clearRows();
  }, "p_form_Subcontracting_Plan.u_ydj_cnt");

  useValuesChange(({ args }) => {
      hidenKey()
    }, "p_form_Subcontracting_Plan.u_zb_type");
  ////////////////////////////////////////////////////////////--dgrid--////////////////////////////////////////////////////////////
  if (dgrid) {
    console.log("dgrid is reayd");
    $NG.updateUI((updater) => {
      const fields = ["u_sy_qty", "u_planned_qty", "u_qdht_qty"];
      fields.forEach((field) => {
        updater.editGrid.p_form_Subcontracting_Plan_d[field].setProps({
          hidden: true, //隐藏
        });
      });
    });
  }

  useDataIndexChange(({ args, table }) => {
    var gridTab = $NG.getCmpApi("p_form_Subcontracting_Plan_d");
    var row = args[0];
    row.u_jhhsdj = row.u_jhws_prc * Number(1 + Number(row.u_sl));
    gridTab.updateRow(row);
  }, "p_form_Subcontracting_Plan_d.u_jhws_prc");

  useDataIndexChange(({ args, table }) => {
    var gridTab = $NG.getCmpApi("p_form_Subcontracting_Plan_d");
    var row = args[0];
    row.u_jhws_prc = row.u_jhhsdj / Number(1 + Number(row.u_sl));
    gridTab.updateRow(row);
  }, "p_form_Subcontracting_Plan_d.u_jhhsdj");

  useUpdateRow(({ args, table }) => {
    // var gridTab = $NG.getCmpApi("p_form_Subcontracting_Plan_d");
    // const row = args[0];
    // gridTab.updateRow(row);
  }, "p_form_Subcontracting_Plan_d");
  updateMx()
  async function updateMx(params) {
    const rows = dgrid.getRows();
    console.log(mstform.getItem('phid_pc').getText());
    
    // 使用 for...of 替代 forEach 以支持 await
    for (const row of rows) {
        try {
            // 将回调转为 Promise 以便使用 await
            const res = await new Promise((resolve, reject) => {
                console.log(`debug`,`'定价完成' and 1=1 and itemno = '${row.u_sub_item_EXName}' and phid_pc = '${mstform.getItem('phid_pc').getValue()}'` );
                $NG.execServer("getDjxqc", { 
                    u_staus: `'定价完成' and 1=1 and itemno = '${row.u_sub_item_EXName}' and phid_pc = '${mstform.getItem('phid_pc').getValue()}'` 
                }, (res) => resolve(res));
            });
            
            // 创建当前行的独立引用（避免异步覆盖）
            const currentRow = row; 
            
            if (res.count === 0) {
                currentRow.u_djstatus = '1';
                console.log('状态设置为1:', currentRow.u_djstatus);
            } else {
                const parsedData = JSON.parse(res.data);
                const allRecords = parsedData.flatMap(item => item.extendObjects || []);
                
                if (allRecords.length === 0) {
                    console.log("无有效数据");
                    currentRow.u_djstatus = 1;
                } else {
                    const currentTime = Date.now();
                    const closestRecord = allRecords.reduce((prev, curr) => {
                        const prevDiff = Math.abs(new Date(prev.u_date) - currentTime);
                        const currDiff = Math.abs(new Date(curr.u_date) - currentTime);
                        return currDiff < prevDiff ? curr : prev;
                    });
                    console.log(closestRecord);
                    // 批量更新属性（减少多次赋值）
                    Object.assign(currentRow, {
                        u_djstatus: 3,
                        u_calibrate_prc_vat: closestRecord.u_zb_prc_vat,
                        u_calibrate_prc: closestRecord.u_zb_prc,
                        u_zb_rate: closestRecord.u_zb_rate,
                        u_djfzr: closestRecord.u_director_phid,
                        u_djfzr_EXName: closestRecord.u_director_name,
                        u_dj_dt: closestRecord.dj_dt,
                        u_djfzr: closestRecord.u_person
                    });
                }
            }
            

        } catch (error) {
            console.error("处理行时出错:", error);
            // 可选：标记错误状态
            row.u_error = true; 
        }
    }
    
    // 最终统一刷新视图（避免频繁重绘）
    dgrid.refreshView();
}
  ////////////////////--dgrid:useUpdateRows--////////////////////
  useUpdateRows(({ args }) => {
    updateMx()
    let total = 0
    dgrid.getRows().forEach((items) => {
      getEqDInfoByphid(items);
      console.log(items);
      

      // 剩余数量
      items.u_sy_qty = (Number(items.u_plan_qty) || 0);
      items.u_total_plan_qty = (Number(items.u_plan_qty) || 0) + (Number(items.u_planned_qty) || 0);

      // 计算含税金额：数量 * 含税单价
      items.u_plan_hs_amt = (Number(items.u_plan_qty) || 0) * (Number(items.u_jhhsdj) || 0);
      items.u_plan_ws_amt = (Number(items.u_plan_qty) || 0) * (items.u_jhhsdj / Number(1 + Number(items.u_sl || 0)));
      total += items.u_plan_hs_amt;
      if((Number(items.u_total_plan_qty) || 0) > (Number(items.u_ljshsl) || 0)){
          $NG.alert("警告：累计申请数量（含本次）超出深化数量，请重新填写！");
          items.u_plan_qty = 0
          items.u_total_plan_qty = items.u_plan_qty + items.u_planned_qty;
      }

      if (Number(items.u_jhws_prc) > Number(items.u_nfb_prc)) {
        $NG.alert("警告：超出拟分包未税单价");
        items.u_jhws_prc = null;
      }
      if ((Number(items.u_total_plan_qty) || 0) > Number(items.u_sub_qty)) {
        $NG.alert("警告：计划数量超出拟分包数量");
        items.u_plan_qty = null;
      }
    });
    console.log(total);
    
    $NG.updateState((updater) => {
			updater.data.p_form_Subcontracting_Plan.setProps({
				u_bqjhhsje: total,

			});
		});
    dgrid.refreshView();
  }, "p_form_Subcontracting_Plan_d");

  ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
  getFbzbjhQtyBySbqd()
  async function getFbzbjhQtyBySbqd(){
    const phid_pc = mstform.getItem("phid_pc").getValue()
    if(!phid_pc) return
    $NG.execServer("getFbzbjhQtyBySbqd",{phid_pc},(res)=>{
      console.log(`数量申请情况`,res);
      if(res.count == 0) return 
      const _data = JSON.parse(res.data).reduce((value,item)=>{
        value.push({...item.extendObjects})
        return value
      },[])
      window._catch_ljQty = _data
    })
  }

  ////////////////////--新增设备清单--////////////////////
  async function addEqClick() {
    if (!mstform.getItem("phid_pc").getValue()) {
      $NG.alert("请先选择项目");
      return;
    }
    if (!mstform.getItem("u_zb_type").getValue()) {
      $NG.alert("请先选择招标类型");
      return;
    }
  //   let sqlFilter = `m.phid_pc = ${mstform.getValues().phid_pc} and (d.u_qty > subplan.u_plan_qty or subplan.u_plan_qty is null) `;
    let sqlFilter = `m.phid_pc = ${mstform.getValues().phid_pc}`;
    let cntFliter = ``;
    // 获取招标类型
    const u_zb_type = mstform.getItem("u_zb_type").getValue()
    // 清空缓存
    window._catch_fbCnt = []
    switch(u_zb_type){
      case "01":
          //等待获取已定价合同明细信息
          const res = await getYdjCntDetailInfo()
          console.log(`查询结果`,res);
          switch(res){
              case 0:
                  $NG.alert("请先选择已定价合同")
                  return
              case -1:
                  $NG.alert("当前已定价合同明细数据为空！")
                  return
          }
          // 将元素转换字符串
          window._catch_fbCnt = window._catch_fbCnt.map(item=>{
              return String(item)
          })
          console.log(`合同明细缓存打印`,window._catch_fbCnt);
          sqlFilter = `d.u_sub_item in (${window._catch_fbCnt.join(",")})`
          break
      case "02":
          const phid = mstform.getItem("u_yztjsq").getValue()
          if(!phid) {
              $NG.alert("业主推荐为空请填写")
              return
          }
          window._catch_yztjInfo = []
          // 等待获取业主推荐
          await getYztDetailInfo()
          console.log(`业主推荐申请缓存`,window._catch_yztjInfo);
          sqlFilter = `d.u_sub_item in (${window._catch_yztjInfo.join(",")})`
          break
      case "03":
          const phid_pc = mstform.getItem("phid_pc").getValue()
          if(!phid_pc) return
          sqlFilter = `m.phid_pc = ${phid_pc}`
          break;
      default:
          sqlFilter = ""
    }

    console.log(`条件`,sqlFilter);
    $NG.external
      .openNGHelp({
        type: "NGMultipleHelp",
        helpId: "shsjqd_subplan",
        valueField: "phid",
        labelField: "d.u_equipment_list_name",
        clientSqlFilter: sqlFilter,
      })
      .then((data) => {
        console.log(data);
        // console.log(`m.phid_pc = ${mstform.getItem("phid_pc").getValue()} and m.u_cnt = '${mstform.getItem("u_cnt").getValue()}'`);
        if (Array.isArray(data) && data.length > 0) {
          console.log(`帮助数据`,data);
          var gridArr = [];
          var gridCount = data.length;
          console.log(gridCount);
          for (var i = 0; i < gridCount; i++) {
              const el = data[i].origin
            var gridObj = {};
            let ljqty = 0
            // 寻找之前申请了多少数量
            console.log(`累计数量缓存`,window._catch_ljQty);
            if(window._catch_ljQty){
              window._catch_ljQty.forEach(item=>{
                if(item.sbqd_phid == el.u_equipment_item){
                  ljqty = (Number(item.total_qty) || 0)
                }
              })
            }
            gridObj.u_eq_no = el.u_equipment_list_no
            gridObj.u_eq_name = data[i].origin.u_equipment_item; //设备清单id
            gridObj.u_eq_name_EXName = data[i].origin.u_equipment_list_name; //设备清单名称
            gridObj.u_sub_item = el.u_sub_item
            gridObj.u_sub_item_EXName = el.itemno
            gridObj.u_sub_item_name = el.itemname
            gridObj.u_nfbx_type = el.flphid
            gridObj.u_nfbx_type_EXName = el.flname
            gridObj.u_sub_item_spec = el.spec
            gridObj.u_sub_item_msunit = el.msphid
            gridObj.u_sub_item_msunit_EXName = el.Msname
            gridObj.u_total_plan_qty = ljqty
            gridObj.u_planned_qty = ljqty
            gridObj.u_sub_qty = el.u_sub_qty
            gridObj.u_sl = el.u_sub_tax_rate
            gridObj.u_nfb_prc = el.u_sub_prc
            gridObj.u_nfbhs_prc = el.u_sub_prc_vat
            gridObj.u_nfbcbhs = el.u_sub_cost_vat
            gridObj.u_nfbcbws = el.u_sub_cost
            gridObj.u_source_id = el.phid
            gridObj.u_ljshsl = (Number(el.u_u_total_shsj) || 0)
            // gridObj.u_planned_qty = data[i].origin.u_plan_qty; //已申请数量
            // gridObj.u_plan_qty = data[i].origin.u_sub_qty - (data[i].origin.u_plan_qty || 0); //本次申请数量
            gridObj.u_jhws_prc = data[i].origin.u_sub_prc; //本次计划未税单价
            gridObj.u_jhhsdj = data[i].origin.u_sub_prc_vat; //本次计划含税单价
            console.log(`添加数据`,gridObj);
            gridArr.push(gridObj);
          }
          console.log(gridArr);
          dgrid.addRows(gridArr);
          dgrid.refreshView();
        }
      });
  }
  // select * from p_form_detailed_design_d d     left join p_form_equipment_list_d sb on d.u_equipment_item=sb.phid     LEFT JOIN itemdata sub ON sub.phid = d.u_sub_item     LEFT JOIN p_form_detailed_design m ON m.phid = d.pphid     LEFT JOIN msunit ON msunit.phid = d.u_unit     LEFT JOIN pcm3_cnt_d cnt ON cnt.phid = d.u_cnt_d     LEFT JOIN fg_simple_data revenue_type ON revenue_type.phid = d.u_revenue_type     left join (         select             m.phid_pc,             u_eq_name,             sum(u_plan_qty) ljsqsl         from             p_form_Subcontracting_Plan m             left join p_form_Subcontracting_Plan_d d on d.pphid = m.phid         group by             m.phid_pc,             d.u_eq_name     ) subplan on subplan.u_eq_name = d.phid and subplan.phid_pc = m.phid_pc
  // left join msunit dw on dw.phid = sub.phid_unit
  // left join res_bs fl on fl.phid = sub.phid_resbs
  // 获取已定价合同信息
  async function getYdjCntDetailInfo(){
      const cnt = mstform.getItem("u_ydj_cnt").getValue()
      if(!cnt) return 0
      await $NG.execServer("getYdjCntDetailInfo",{cnt},(res)=>{
          console.log(`合同明细`,res,cnt);
          if(res.count == 0){
              return -1
          } else {
              window._catch_fbCnt = JSON.parse(res.data).reduce((value,item)=>{
                  value.push(item.extendObjects.phid_itemdata)
                  return value
              },[])
              console.log(`加载时打印`,[...window._catch_fbCnt]);
              return 1
          }
      })
  }

  // 获取业主推荐申请无聊信息
  async function getYztDetailInfo(){
      const phid = mstform.getItem("u_yztjsq").getValue()
      if(!phid) return 
      await $NG.execServer("getYztDetailInfo",{phid},(res)=>{
          console.log(`业主推荐申请数据`,res);
          if(res.data == 0) return
          window._catch_yztjInfo = JSON.parse(res.data).reduce((value,item)=>{
              const el = item.extendObjects
              value.push(el.u_wl_no)
              return value
          },[])
      })
  }


  function getProjectInfo(isReturn = false, phid = mstform.getItem("phid_pc").getValue(), fun) {
    if (!phid) {
      return;
    }
    try {
      setTimeout(() => {
        $NG.execServer("getPtInfoByPhid", { phid: phid }, (res) => {
          if (res.count !== 0) {
            const _data = JSON.parse(res.data)[0].extendObjects;
            console.log(`获取项目信息`, _data);
            if (isReturn) {
              fun(_data);
            } else {
              $NG.updateState((updater) => {
                updater.data.p_form_Subcontracting_Plan.setProps({
                  u_pc_no: _data.pc_no, //项目编码
                });
              });
            }
          }
        });
      }, 100);
    } catch (err) {
      $NG.alert("获取项目信息发生失败请检查~");
    }
  }

  function setTitle() {
    if(page.oType != 'add') return
    if (!mstform.getItem("phid_pc").getValue()) return;
    console.log(`setTitle`);
    $NG.execServer("GetZbTime", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
      if (res.count == 0) {
        $NG.updateState((updater) => {
          updater.data.p_form_Subcontracting_Plan.setProps({
            bill_name: `${mstform.getItem("phid_pc").getText()}第1次招标计划`,
          });
        });
      } else {
        const _data = JSON.parse(res.data)[0].extendObjects;
        $NG.updateState((updater) => {
          updater.data.p_form_Subcontracting_Plan.setProps({
            bill_name: `${mstform.getItem("phid_pc").getText()}第${_data.count + 1}次招标计划`,
          });
        });
      }
    });
  }

  //根据当前日期获取工作周期
  function getInDate() {
    $NG.execServer("getInDate", {}, function (res) {
      if (res.count !== 0) {
        const _data = JSON.parse(res.data)[0].extendObjects;
        $NG.updateState((updater) => {
          updater.data.p_form_Subcontracting_Plan.setProps({
            phid_cycle: {
              label: _data.bill_name,
              value: _data.phid,
            },
          });
        });
      }
    });
  }

  //合同根据项目ID过滤，//0528后加标前的业主推荐申请没有项目，无法根据项目再进行过滤
  function FilterByPhidPc() {
    /*$NG.updateUI((updater, state) => {
      console.log("过滤参数检查", updater);
      updater.fieldSetForm.p_form_Subcontracting_Plan.u_yztjsq.setProps({
        onBeforeOpen: async () => {
          var phid_pc = $NG.getCmpApi("p_form_Subcontracting_Plan").getItem("phid_pc").getValue();
          if (!phid_pc) {
            $NG.alert("请先选择项目");
            return false;
          } else {
            return true;
          }
        },
        ...(!!$NG.getCmpApi("p_form_Subcontracting_Plan").getItem("phid_pc").getValue() && {
          clientSqlFilter: {
            "a.phid_pc": $NG.getCmpApi("p_form_Subcontracting_Plan").getItem("phid_pc").getValue(),
          },
        }),
      });
    });*/
    $NG.updateUI((updater, state) => {
      console.log("过滤参数检查", updater);
      updater.fieldSetForm.p_form_Subcontracting_Plan.u_ydj_cnt.setProps({
        onBeforeOpen: async () => {
          var phid_pc = $NG.getCmpApi("p_form_Subcontracting_Plan").getItem("phid_pc").getValue();
          if (!phid_pc) {
            $NG.alert("请先选择项目");
            return false;
          } else {
            return true;
          }
        },
        ...(!!$NG.getCmpApi("p_form_Subcontracting_Plan").getItem("phid_pc").getValue() && {
          clientSqlFilter: {
            "pcm3_cnt_m.phid_pc": $NG.getCmpApi("p_form_Subcontracting_Plan").getItem("phid_pc").getValue(),
          },
        }),
      });
    });
  }

  function isRead() {
    const type = mstform.getItem("u_zb_type").getValue(); //获取值
    console.log(`类型`, type);
    if (type == "01") {
      $NG.updateUI((updater) => {
        const fields = ["u_yztjsq"];
        fields.forEach((field) => {
          // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
          updater.fieldSetForm.p_form_Subcontracting_Plan[field].setProps({
            required: false, //必输
            disabled: true, //只读
          });
        });
      });
      $NG.updateUI((updater) => {
        const fields = ["u_ydj_cnt"];
        fields.forEach((field) => {
          // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
          updater.fieldSetForm.p_form_Subcontracting_Plan[field].setProps({
            required: true, //必输
            disabled: false, //只读
          });
        });
      });
    }

    if (type == "02") {
      $NG.updateUI((updater) => {
        const fields = ["u_ydj_cnt"];
        fields.forEach((field) => {
          // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
          updater.fieldSetForm.p_form_Subcontracting_Plan[field].setProps({
            required: false, //必输
            disabled: true, //只读
          });
        });
      });
      $NG.updateUI((updater) => {
        const fields = ["u_yztjsq"];
        fields.forEach((field) => {
          // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
          updater.fieldSetForm.p_form_Subcontracting_Plan[field].setProps({
            required: true, //必输
            disabled: false, //只读
          });
        });
      });
    }
    if (type == "03") {
      $NG.updateUI((updater) => {
        const fields = ["u_yztjsq"];
        fields.forEach((field) => {
          // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
          updater.fieldSetForm.p_form_Subcontracting_Plan[field].setProps({
            required: false, //必输
            disabled: true, //只读
          });
        });
      });
      $NG.updateUI((updater) => {
        const fields = ["u_ydj_cnt"];
        fields.forEach((field) => {
          // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
          updater.fieldSetForm.p_form_Subcontracting_Plan[field].setProps({
            required: false, //必输
            disabled: true, //只读
          });
        });
      });
    }
  }

  function getEqDInfoByphid(items) {
      return 
    if (items.u_eq_name && !items.u_eq_no) {
      $NG.execServer("getEqDInfoByphid", { phid: items.u_eq_name }, (res) => {
        console.log("功能扩展数据:getEqDInfoByphid");
        try {
          const data = JSON.parse(res.data)[0].extendObjects;
          items.u_eq_no = data.u_equipment_list_no;
          items.u_sub_item = data.u_sub_item;
          items.u_sub_item_EXName = data.u_sub_no;
          items.u_sub_item_name = data.u_sub_item_name;
          items.u_nfbx_type = data.u_sub_item_category;
          items.u_nfbx_type_EXName = data.u_pc_subitem_category;
          items.u_sub_item_spec = data.u_spec;
          items.u_sub_item_spec_EXName = data.u_sub_ggxh;
          items.u_sub_item_msunit = data.u_sub_item_msunit; //拟分包计量单位
          items.u_sub_item_msunit_EXName = data.u_subunit_name;
          items.u_sub_qty = data.u_sub_qty; //拟分包项数量
          items.u_nfb_prc = data.u_sub_prc; //拟分包未税单价
          items.u_nfbhs_prc = data.u_sub_prc_vat; //拟分包含税单价
          items.u_nfbcbws = data.u_sub_cost; //拟分包成本未税
          items.u_nfbcbhs = data.u_sub_cost_vat; //拟分包成本含税
          items.u_sl = data.u_sub_tax_rate; //税率
          items.u_source_id = data.phid; //来源id
        } catch (error) {
          console.log("功能扩展报错:getEqDInfoByphid");
        }
        dgrid.refreshView();
      });
    }
  }

  // 部分字段吟唱逻辑
  hidenKey()
  function hidenKey(){
      const u_zb_type = mstform.getItem("u_zb_type").getValue()
      switch(u_zb_type){
          case "01":
              $NG.updateUI((updater)=>{
                  updater.fieldSetForm.p_form_Subcontracting_Plan.u_ydj_cnt.setProps({
                      hidden:false,
                      require:true
                  })
                  updater.fieldSetForm.p_form_Subcontracting_Plan.u_yztjsq.setProps({
                      hidden:true,
                      require:false
                  })
              })
              break;
          case '02':
              $NG.updateUI((updater)=>{
                  updater.fieldSetForm.p_form_Subcontracting_Plan.u_ydj_cnt.setProps({
                      hidden:true,
                      require:false
                  })
                  updater.fieldSetForm.p_form_Subcontracting_Plan.u_yztjsq.setProps({
                      hidden:false,
                      require:true
                  })
              })
              break
          default:
              $NG.updateUI((updater)=>{
                  updater.fieldSetForm.p_form_Subcontracting_Plan.u_ydj_cnt.setProps({
                      hidden:true,
                      require:false
                  })
                  updater.fieldSetForm.p_form_Subcontracting_Plan.u_yztjsq.setProps({
                      hidden:true,
                      require:false
                  })
              })
      }
  }
});

//   if (!items.u_eq_no) {
//     $NG.execServer("getEqSubInfo", { phid_pc: phid_pc, sub_item: items.u_sub_item }, function (res) {
//       if (res.count > 0) {
//         const datas = JSON.parse(res.data)[0].extendObjects;
//         items.u_eq_no = datas.u_equipment_list_no;
//         items.u_eq_name = datas.phid;
//         items.u_eq_name_EXName = datas.u_equipment_list_name;
//         items.u_sub_qty = datas.u_sub_qty;
//         items.u_nfb_prc = datas.u_sub_prc;
//         items.u_nfbhs_prc = datas.u_sub_prc_vat;
//         items.u_nfbcbws = datas.u_sub_cost;
//         items.u_nfbcbhs = datas.u_sub_cost_vat;
//         items.u_sl = datas.u_sub_tax_rate;
//         if (datas.phid) {
//           $NG.execServer("getSubPlanSumInfo", { phid_pc: phid_pc, eq_phid: datas.phid, phid: items.phid || 0 }, function (res) {
//             if (res.count > 0) {
//               const datas1 = JSON.parse(res.data)[0].extendObjects;
//             //   items.u_planned_qty = Number(datas1.u_plan_qty || 0);
//               items.u_plan_qty = Number(datas.u_sub_qty) - Number(datas1.u_plan_qty || 0);
//               items.u_plan_hs_amt = (Number(datas.u_sub_qty) - Number(datas1.u_plan_qty || 0)) * items.u_jhhsdj;
//             } else {
//               console.log("功能扩展没有数据：" + "getSubPlanSumInfo");
//             }
//             dgrid.refreshView();
//           });
//         }
//       } else {
//         console.log("功能扩展没有数据：" + "getEqSubInfo");
//       }
//       dgrid.refreshView();
//     });
//   }

// // 明细表获取累计分包招标计划的数量
// function getSubPlanSumInfo(params) {
//   var phid_pc = mstform.getItem("phid_pc").getValue();
//   dgrid.getRows().forEach((items) => {
//     if (!items.u_eq_no) {
//       $NG.execServer("getSubPlanSumInfo", { phid_pc: phid_pc, eq_phid: items.u_eq_name, phid: items.phid || 0 }, function (res) {
//         console.log(`res`, res);
//         if (res.count > 0) {
//           const datas = JSON.parse(res.data)[0].extendObjects;
//           items.u_planned_qty = Number(datas.u_plan_qty);
//         } else {
//           console.log("功能扩展没有数据：" + "getEqSubInfo");
//         }
//       });
//     }
//   });
// }
